-- 中毒
local DEFAULT_DAMAGE = 10
local DEFAULT_DURATION = 20
local DEFAULT_PERIOD = 1.5

local function ApplyDisplay(inst)
    local dis = SpawnPrefab("display_effect")
    local rad = inst:GetPhysicsRadius(0)
    local x, y, z = inst.Transform:GetWorldPosition()
    dis.Transform:SetPosition(x, y + .5 * rad , z)
    dis:Display("中毒", 32, {0, 1, 0})
end

local Poison = Class(function(self, inst) 
    self.inst = inst
    self.duration = 0
    self.damage = 0
    self.damage_period = DEFAULT_PERIOD
    
    self.current_period = 0
    self.attacker = nil
end)

function Poison:Effect()
    local inst = self.inst 
    if inst.components.health and not inst.components.health:IsDead() then
        inst.components.health:DoDelta(-self.damge, nil, "poison", nil, self.attacker)
        ApplyDisplay(inst)
    else
        self:OverTime()
    end
end

function Poison:Poison(damge, duration, attacker)
    local inst = self.inst 
    if inst.components.colourtweener == nil then
        inst:AddComponent("colourtweener")
    end
    if inst.components.health and not inst.components.health:IsDead() then
        self.attacker = attacker
        self:Start(damge or DEFAULT_DAMAGE, duration or DEFAULT_DURATION)
    end
end

function Poison:Start(damge, duration)
    self.damge = damge or DEFAULT_DAMAGE
    self.duration = duration or DEFAULT_DURATION
    self.inst.components.colourtweener:StartTween({0,1,0,1}, 0)
    self.inst:StartUpdatingComponent(self)
end

function Poison:OverTime()
    self.duration = 0
    self.attacker = nil
    if self.inst.components.colourtweener then
        self.inst.components.colourtweener:StartTween({1,1,1,1}, 0)
    end
    self.inst:StopUpdatingComponent(self)
end

function Poison:OnUpdate(dt)
    self.current_period = self.current_period + dt
    if self.current_period >= self.damage_period then
        self.current_period = 0
        self:Effect()
    end
    self.duration = self.duration - dt 
    if self.duration <= 0 then
        self:OverTime()
    end
end

function Poison:OnSave()
    return {
        duration = self.duration,
        damage = self.damage,
        damage_period = self.damage_period,
        
        current_period = self.current_period,
    }
end

function Poison:OnLoad(data)
	if data ~= nil then
        self.duration = data.duration or 0
        self.damage = data.damage or 0
        self.damage_period = data.damage_period or DEFAULT_PERIOD
        
        self.current_period = data.current_period or 0
    end

    if self.duration > 0 and self.damage > 0 then
        self:Poison()
    end
end

return Poison